import { useEffect } from "react";
import { useObject } from ".";

const defaultState = {
  fetching: false,
  data: undefined,
  error: undefined,
};

// const { data, fetching, refetch } = useFetch([fetchUser, params])

export const useFetch = ([fetcher, ...params], { enable, keepPrevious }) => {
  const [state, update, setState] = useObject(defaultState);

  const fetch = async (_) => {
    if (keepPrevious) {
      update({ ...state, fetching: true, error: undefined })
    } else {
      setState({ fetching: true })
    }

    try {
      const res = await fetcher(params)
      update({ fetching: false, data: res })
    } catch {
      update({ fetching: false, error: true })
    }
  };

  useEffect(() => {
    if (enable && !state.fetching) {
      fetch();
    }
  });

  return { ...state, refetch: fetch }
};
